<template>
  <view class="pickup-container">
    <!-- 顶部导航 -->
    <!-- 提货表单 -->
    <view class="pickup-form">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">提货人信息</view>
        
        <!-- 姓名 -->
        <view class="form-item">
          <view class="item-label">姓名</view>
          <view class="item-content">
            <input 
              type="text" 
              placeholder="请输入姓名" 
              class="input-field"
              v-model="formData.name"
              @blur="validateName"
            />
          </view>
          <view class="error-tip" v-if="formErrors.name">{{ formErrors.name }}</view>
        </view>
        
        <!-- 手机号 -->
        <view class="form-item">
          <view class="item-label">手机号</view>
          <view class="item-content">
            <input 
              type="number" 
              placeholder="请输入手机号" 
              class="input-field"
              v-model="formData.phone"
              @blur="validatePhone"
            />
          </view>
          <view class="error-tip" v-if="formErrors.phone">{{ formErrors.phone }}</view>
        </view>
      </view>
      
      <!-- 提货商品信息 -->
      <view class="form-section">
        <view class="section-title">提货商品信息</view>
        
        <!-- 商品名称 -->
        <view class="form-item">
          <view class="item-label">商品名称</view>
          <view class="item-content">
            <picker 
              mode="selector" 
              :range="productList" 
              :range-key="'title'" 
              @change="onProductChange"
              :value="selectedProductIndex"
            >
              <view class="picker">
                {{ selectedProduct ? selectedProduct.title : '请选择商品' }}
                <text class="iconfont icon-arrow-down"></text>
              </view>
            </picker>
          </view>
          <view class="error-tip" v-if="formErrors.product">{{ formErrors.product }}</view>
        </view>
        
        <!-- 提货数量 -->
        <view class="form-item">
          <view class="item-label">提货数量</view>
          <view class="item-content">
            <view class="quantity-control">
              <button class="quantity-btn" @click="decreaseQuantity">-</button>
              <input 
                type="number" 
                class="quantity-input"
                v-model.number="formData.quantity"
                @blur="validateQuantity"
              />
              <button class="quantity-btn" @click="increaseQuantity">+</button>
            </view>
            <!-- <view class="available-stock" v-if="selectedProduct">
              库存: {{ selectedProduct.stock }} 件
            </view> -->
          </view>
          <view class="error-tip" v-if="formErrors.quantity">{{ formErrors.quantity }}</view>
        </view>
      </view>
      
      <!-- 邮寄信息 -->
      <view class="form-section">
        <view class="section-title">邮寄信息</view>
        
        <!-- 邮寄地址 -->
        <view class="form-item" style="    align-items: flex-start;">
          <view class="item-label">邮寄地址:</view>
          <view class="item-content">
            <textarea 
              placeholder="请输入详细地址" 
              class="textarea-field"
              v-model="formData.address"
              @blur="validateAddress"
            ></textarea>
          </view>
          <view class="error-tip" v-if="formErrors.address">{{ formErrors.address }}</view>
        </view>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-button">
      <button 
        class="btn-submit" 
        :disabled="!isFormValid"
        @click="submitForm"
      >
        提交申请
      </button>
    </view>
  </view>
</template>

<script>
	import {
		request
	} from '@/utils/request.js'
export default {
  data() {
    return {
		userInfo:{},
      // 表单数据
      formData: {
        name: '',
        phone: '',
        productId: '',
        quantity: 1,
        address: ''
      },
      
      // 表单错误信息
      formErrors: {
        name: '',
        phone: '',
        product: '',
        quantity: '',
        address: ''
      },
      
      // 商品列表
      productList: [
        { id: '1', name: '高级营养蛋白粉', stock: 999999 },
        { id: '2', name: '天然维生素C片', stock: 999999 },
        { id: '3', name: '深海鱼油软胶囊', stock: 999999 },
        { id: '4', name: '益生菌胶囊', stock: 999999 },
        { id: '5', name: '胶原蛋白口服液', stock: 999999 }
      ],
      
      // 当前选中的商品索引和信息
      selectedProductIndex: 0,
      selectedProduct: null
    }
  },

  computed: {
    // 表单是否有效
    isFormValid() {
      return !this.formErrors.name && 
             !this.formErrors.phone && 
             !this.formErrors.product && 
             !this.formErrors.quantity && 
             !this.formErrors.address &&
             this.formData.name && 
             this.formData.phone && 
             this.formData.productId && 
             this.formData.quantity > 0 && 
             this.formData.address;
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 选择商品
    onProductChange(e) {
      this.selectedProductIndex = e.detail.value;
      this.formData.productId = this.productList[this.selectedProductIndex].id;
      this.selectedProduct = this.productList[this.selectedProductIndex];
      this.validateProduct();
    },
    
    // 增加数量
    increaseQuantity() {
      if (this.selectedProduct && this.formData.quantity < this.selectedProduct.stock) {
        this.formData.quantity++;
      }
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.formData.quantity > 1) {
        this.formData.quantity--;
      }
    },
    
    // 验证姓名
    validateName() {
      if (!this.formData.name.trim()) {
        this.formErrors.name = '请输入姓名';
      } else {
        this.formErrors.name = '';
      }
    },
    
    // 验证手机号
    validatePhone() {
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!this.formData.phone) {
        this.formErrors.phone = '请输入手机号';
      } else if (!phoneReg.test(this.formData.phone)) {
        this.formErrors.phone = '请输入有效的手机号';
      } else {
        this.formErrors.phone = '';
      }
    },
    
    // 验证商品
    validateProduct() {
      if (!this.formData.productId) {
        this.formErrors.product = '请选择商品';
      } else {
        this.formErrors.product = '';
      }
    },
    
    // 验证数量
    validateQuantity() {
      if (!this.formData.quantity || this.formData.quantity <= 0) {
        this.formErrors.quantity = '请输入有效的数量';
      } else if (this.selectedProduct && this.formData.quantity > this.selectedProduct.stock) {
        this.formErrors.quantity = `库存不足，最大可提货${this.selectedProduct.stock}件`;
      } else {
        this.formErrors.quantity = '';
      }
    },
    
    // 验证地址
    validateAddress() {
      if (!this.formData.address.trim()) {
        this.formErrors.address = '请输入邮寄地址';
      } else if (this.formData.address.length < 5) {
        this.formErrors.address = '地址长度不能少于5个字符';
      } else {
        this.formErrors.address = '';
      }
    },
    getShopList(){
    		request({
    			url: 'index/goods-list',
    			method: 'get',
    			// data: { username:this.username,password:this.password,openid:uni.getStorageSync("openid")}
    		}).then(res => {
    			if (res.status == 200) {
    				console.log(res.data)
					const newArray = res.data.list.map(item => ({
					  ...item,          // 保留原有属性
					  stock: 9999999      // 添加新属性
					}));
					this.productList = newArray
					this.selectedProduct = this.productList[this.selectedProductIndex];
					this.formData.productId = this.selectedProduct.id;
    				// this.products = res.data.list
    			} else {
    				uni.showToast({
    					title: res.message,
    					icon: 'none',
    					duration: 2000
    				});
    			}
    		}).catch((err) => {
    			uni.showToast({
    				title: err.message,
    				icon: 'none',
    				duration: 2000
    			});
    		})
    	},
    	sub(){
    		request({
    			url: 'index/approval-sub',
    			method: 'post',
    			data:{
    				num:'',
    				discription:'',
    				name:'',
    				tel:'',
    				address:'',
    				id:'',
    				gid:'',
    			}
    			// data: { username:this.username,password:this.password,openid:uni.getStorageSync("openid")}
    		}).then(res => {
    			if (res.status == 200) {
    				console.log(res.data)
				
    			} else {
    				uni.showToast({
    					title: res.message,
    					icon: 'none',
    					duration: 2000
    				});
    			}
    		}).catch((err) => {
    			uni.showToast({
    				title: err.message,
    				icon: 'none',
    				duration: 2000
    			});
    		})
    	},
    
    // 提交表单
    submitForm() {
      // 再次验证所有字段
      this.validateName();
      this.validatePhone();
      this.validateProduct();
      this.validateQuantity();
      this.validateAddress();
      
      // 如果表单无效，不提交
      if (!this.isFormValid) return;
      
      // 显示加载提示
    
      request({
      	url: 'index/approval-sub',
      	method: 'post',
      	data:{
      		num:this.formData.quantity,
      		discription:'',
      		name:this.formData.name,
      		tel:this.formData.phone,
      		address:this.formData.address,
      		aid:this.userInfo.uid,
      		gid:this.formData.productId,
      	}
      	// data: { username:this.username,password:this.password,openid:uni.getStorageSync("openid")}
      }).then(res => {
		  uni.hideLoading();
      	if (res.status == 200) {
      		console.log(res.data)
			// 隐藏加载提示
			
			// 显示成功提示
			uni.showToast({
			  title: '申请提交成功',
			  icon: 'success',
			  duration: 2000
			});
			
			// 返回上一页
			setTimeout(() => {
			  uni.navigateBack();
			}, 2000);
      	
      	} else {
      		uni.showToast({
      			title: res.message,
      			icon: 'none',
      			duration: 2000
      		});
      	}
      }).catch((err) => {
		  uni.hideLoading();
      	uni.showToast({
      		title: err.message,
      		icon: 'none',
      		duration: 2000
      	});
      })
    }
  },
  
  // 页面加载时初始化选中的商品
  onLoad() {
	  if (uni.getStorageSync('userInfo')) {
	  	this.userInfo = uni.getStorageSync('userInfo')
	  }else{
	  	uni.navigateTo({
	  		url:"/pages/login/login"
	  	})
	  }
	  this.getShopList()
   
  }
}
</script>

<style lang="scss" scoped>
.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.pickup-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 顶部导航 */
.page-header {
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  
  .header-left, .header-right {
    width: 80rpx;
    text-align: center;
  }
  
  .header-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }
  
  .icon-arrow-left {
    font-size: 40rpx;
    color: #666;
  }
}

/* 提货表单 */
.pickup-form {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.form-section {
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.form-item {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
  
  &:last-child {
    border-bottom: none;
  }
  
  .item-label {
    width: 200rpx;
    font-size: 30rpx;
    color: #666;
  }
  
  .item-content {
    flex: 1;
    position: relative;
    
    .input-field {
      width: 100%;
      height: 60rpx;
      font-size: 30rpx;
      color: #333;
      text-align: right;
    }
    
    .textarea-field {
      width: 100%;
      min-height: 120rpx;
      font-size: 30rpx;
      color: #333;
      text-align: left;
      padding: 10rpx 0;
    }
    
    .picker {
      width: 100%;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 30rpx;
      color: #333;
      text-align: right;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      
      .icon-arrow-down {
        margin-left: 10rpx;
        color: #999;
      }
    }
    
    .quantity-control {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      
      .quantity-btn {
        width: 60rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        background-color: #f5f5f5;
        border-radius: 50%;
        font-size: 36rpx;
        color: #666;
		padding: 0;
      }
      
      .quantity-input {
        width: 120rpx;
        height: 60rpx;
        text-align: center;
        font-size: 32rpx;
        color: #333;
      }
    }
    
    .available-stock {
      position: absolute;
      right: 0;
      bottom: -30rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .error-tip {
    position: absolute;
    right: 0;
    bottom: 10rpx;
    color: #ff4545;
    font-size: 24rpx;
  }
}

/* 提交按钮 */
.submit-button {
  margin: 40rpx 30rpx;
  
  .btn-submit {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #1677ff;
    color: #fff;
    border-radius: 45rpx;
    font-size: 34rpx;
    text-align: center;
    box-shadow: 0 4rpx 15rpx rgba(22, 119, 255, 0.2);
    opacity: 0.6;
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
    &:not(:disabled) {
      opacity: 1;
      cursor: pointer;
      transition: all 0.3s ease;
      &:hover {
        background-color: #0e62d0;
        box-shadow: 0 6rpx 20rpx rgba(22, 119, 255, 0.3);
      }
    }
  }
}
</style>
